package com.qf.dao.impl;

import com.qf.dao.OrderDao;
import com.qf.domain.Order;
import com.qf.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class OrderDaoimpl implements OrderDao {
    QueryRunner queryRunner = new QueryRunner();

    @Override
    public void addOrder(Order order) {
        Connection connection = DataSourceUtils.getConnection();
        String sql = "insert into tb_order(id,uid,money,status,time,aid) values(?,?,?,?,?,?)";
        Object[] params = {order.getId(), order.getUid(), order.getMoney(), order.getStatus(), order.getTime(), order.getAid()};
        try {
            queryRunner.update(connection, sql, params);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException(throwables);
        } finally {
            DataSourceUtils.closeAll(null, null, connection);
        }
    }

    @Override
    public void UpdateOrderstatus(String id, String s) {
        Connection connection = DataSourceUtils.getConnection();
        String sql = "update tb_order set status=? where id=?";
        try {
            queryRunner.update(connection, sql, s, id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException(throwables);
        } finally {
            DataSourceUtils.closeAll(null, null, connection);
        }
    }

    @Override
    public List<Order> selectUserOne(Integer id) {
        Connection connection = DataSourceUtils.getConnection();
        String sql = "select * from tb_order where uid=?";
        try {
            return queryRunner.query(connection, sql, new BeanListHandler<>(Order.class), id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException(throwables);
        } finally {
            DataSourceUtils.closeAll(null, null, connection);
        }
    }

    @Override
    public Order selectIdOne(String oid) {
        Connection connection = DataSourceUtils.getConnection();
        String sql = "select * from tb_order where id=?";
        try {
            return queryRunner.query(connection, sql, new BeanHandler<>(Order.class), oid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException(throwables);
        } finally {
            DataSourceUtils.closeAll(null, null, connection);
        }
    }
}